require('dotenv').config();
const { NodeSSH } = require('node-ssh');
const path = require('path');
const { execSync } = require('child_process');

const ssh = new NodeSSH();

const config = {
  host: '14.103.234.37',
  username: 'root',
  password: 'Lin65962022_',
  tryKeyboard: true
};

const deployPath = '/var/www/project-management';
const PORT = 3000;
const projectPath = path.join(__dirname, 'project-management');
const distPath = path.join(projectPath, 'dist');

async function deploy() {
  try {
    // 构建项目
    console.log('Building project...');
    process.chdir(projectPath);
    execSync('npm run build', { stdio: 'inherit' });
    
    console.log('Connecting to server...');
    await ssh.connect(config);
    console.log('Connected successfully!');

    // 检查系统类型
    const { stdout: osInfo } = await ssh.execCommand('cat /etc/os-release');
    const isCentOS = osInfo.toLowerCase().includes('centos') || osInfo.toLowerCase().includes('rhel');
    const isUbuntu = osInfo.toLowerCase().includes('ubuntu') || osInfo.toLowerCase().includes('debian');
    
    console.log('OS Type:', isCentOS ? 'CentOS/RHEL' : isUbuntu ? 'Ubuntu/Debian' : 'Unknown');

    // 清理并创建部署目录
    console.log('Preparing deployment directory...');
    await ssh.execCommand(`sudo rm -rf ${deployPath}/*`);
    await ssh.execCommand(`sudo mkdir -p ${deployPath}`);
    await ssh.execCommand(`sudo chown -R ${config.username}:${config.username} ${deployPath}`);
    
    // 上传构建文件
    console.log('Uploading build files...');
    await ssh.putDirectory(distPath, deployPath, {
      recursive: true,
      concurrency: 10,
      tick: function(localPath, remotePath, error) {
        if (error) {
          console.error(`Failed to upload ${localPath} -> ${remotePath}`);
        } else {
          console.log(`Uploaded ${localPath} -> ${remotePath}`);
        }
      }
    });
    
    // 配置 Apache
    if (isCentOS) {
      console.log('Configuring CentOS Apache...');
      
      // 检查 Apache 是否安装
      const { stdout: httpd } = await ssh.execCommand('rpm -qa | grep httpd');
      if (!httpd) {
        console.log('Installing Apache...');
        await ssh.execCommand('sudo dnf install -y httpd');
      }

      // 创建新的配置文件
      const apacheConfig = `
Listen ${PORT}
<VirtualHost *:${PORT}>
    ServerName localhost
    DocumentRoot ${deployPath}
    
    <Directory ${deployPath}>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
        
        # Handle client-side routing
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.html [L]
    </Directory>

    ErrorLog /var/log/httpd/project_error.log
    CustomLog /var/log/httpd/project_access.log combined
</VirtualHost>`;

      await ssh.execCommand(`echo '${apacheConfig}' | sudo tee /etc/httpd/conf.d/project.conf`);
      
      // 检查配置文件
      console.log('Checking Apache configuration...');
      const { stdout: confCheck } = await ssh.execCommand('sudo httpd -t');
      console.log('Config check result:', confCheck);

      // SELinux 设置
      console.log('Configuring SELinux...');
      await ssh.execCommand('sudo setsebool -P httpd_read_user_content 1');
      await ssh.execCommand(`sudo semanage port -a -t http_port_t -p tcp ${PORT} || sudo semanage port -m -t http_port_t -p tcp ${PORT}`);
      
      // 重启 Apache
      console.log('Restarting Apache...');
      await ssh.execCommand('sudo systemctl restart httpd');
      
      // 检查服务状态
      const { stdout: status } = await ssh.execCommand('sudo systemctl status httpd');
      console.log('Apache status:', status);

    } else if (isUbuntu) {
      console.log('Configuring Ubuntu Apache...');
      
      // 检查 Apache 是否安装
      const { stdout: apache2 } = await ssh.execCommand('dpkg -l | grep apache2');
      if (!apache2) {
        console.log('Installing Apache...');
        await ssh.execCommand('sudo apt update && sudo apt install -y apache2');
      }

      // 启用必要的模块
      console.log('Enabling required modules...');
      await ssh.execCommand('sudo a2enmod rewrite');

      // 配置端口
      await ssh.execCommand(`echo "Listen ${PORT}" | sudo tee -a /etc/apache2/ports.conf`);

      // 创建新的配置文件
      const apacheConfig = `
<VirtualHost *:${PORT}>
    ServerName localhost
    DocumentRoot ${deployPath}
    
    <Directory ${deployPath}>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
        
        # Handle client-side routing
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.html [L]
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/project_error.log
    CustomLog \${APACHE_LOG_DIR}/project_access.log combined
</VirtualHost>`;

      await ssh.execCommand(`echo '${apacheConfig}' | sudo tee /etc/apache2/sites-available/project.conf`);
      await ssh.execCommand('sudo a2ensite project.conf');
      
      // 重启 Apache
      console.log('Restarting Apache...');
      await ssh.execCommand('sudo systemctl restart apache2');
      
      // 检查服务状态
      const { stdout: status } = await ssh.execCommand('sudo systemctl status apache2');
      console.log('Apache status:', status);
    }

    // 检查端口是否在监听
    console.log('Checking port status...');
    const { stdout: netstat } = await ssh.execCommand(`sudo netstat -tlpn | grep :${PORT}`);
    console.log('Port status:', netstat);

    // 检查错误日志
    console.log('Checking error logs...');
    if (isCentOS) {
      const { stdout: errorLog } = await ssh.execCommand('sudo tail -n 50 /var/log/httpd/error_log');
      console.log('Apache error log:', errorLog);
    } else if (isUbuntu) {
      const { stdout: errorLog } = await ssh.execCommand('sudo tail -n 50 /var/log/apache2/error.log');
      console.log('Apache error log:', errorLog);
    }

    console.log('Deployment completed!');
    console.log(`Your application is now available at: http://${config.host}:${PORT}`);

  } catch (error) {
    console.error('Deployment failed:', error);
    console.error('Error details:', error.message);
  } finally {
    ssh.dispose();
  }
}

deploy();
